layui.config({
	base: '/static/plugin/build/js/'
}).use(['table', 'laytpl', 'layer', 'ztree', 'laydate','upload'], function() {
	var $ = layui.$;
	var table = layui.table;
	var layer = layui.layer;
	var laytpl = layui.laytpl;
	var upload = layui.upload;
	loadDeptTree();
	renderPostDate();
	//组织机构树初始化
	var setting = {
		check: {
			enable: true,
			chkStyle: "radio",
			radioType: "level"
		},
		view: {
			dblClickExpand: true
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			beforeClick: deptTreeBeforeClick,
			onCheck: deptTreeOnCheck
		}
	};
	//加载组织机构树
	function loadDeptTree() {
		//查询组织机构
		$.get(
			"/mock/department.json",
			function(result) {
				if(result.code == 0) {
					var trees = result.data;
					var zNodes = new Array();
					for(var i = 0; i < trees.length; i++) {
						if(trees[i].id == "11" || trees[i].id == "12") {
							zNodes.push(trees[i]);
						}
					}
					$.fn.zTree.init($("#ztree"), setting, zNodes);
				}
			},
			"json"
		);

	}
	$("#postdeptname").on("click", function() {
		ShowTreeMenu();
	});
	//展示组织机构树
	function ShowTreeMenu() {
		HidenTreeMenu();
		$("#postDeptMenuContent").slideDown("fast");
		$("body").bind("mousedown", TreeOnBodyDown);
	}
	//隐藏组织机构树
	function HidenTreeMenu() {
		$("#postDeptMenuContent").fadeOut("fast");
		$("body").unbind("mousedown", TreeOnBodyDown);
	}

	function TreeOnBodyDown(event) {
		if(!(event.target.id == "postdeptname" || event.target.id == "postDeptMenuContent" || $(event.target).parents("#postDeptMenuContent").length > 0)) {
			HidenTreeMenu();
		}
	}

	function deptTreeBeforeClick(treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("ztree");
		zTree.checkNode(treeNode, !treeNode.checked, null, true);
		return false;
	}

	function deptTreeOnCheck(e, treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("ztree");
		var nodes = zTree.getCheckedNodes(true);
		if(nodes && nodes.length == 1) {
			var postdeptnameObj = $("#postdeptname");
			postdeptnameObj.val(nodes[0].name);
			var postdeptidObj = $("#postdeptid");
			postdeptidObj.val(nodes[0].id);
		}
		HidenTreeMenu()
	}
	//日期表格
	function renderPostDate() {
		//获取当前日期
		var date = new Date();
		var currentDate = date.getFullYear().toString() + "-" + ((date.getMonth() + 1 < 10) ? ("0" + (date.getMonth() + 1).toString()) : (date.getMonth() + 1).toString()) + "-" + ((date.getDate() < 10) ? ("0" + date.getDate().toString()) : date.getDate().toString());

		//渲染发布时间
		layui.laydate.render({
			elem: '#postdate',
			format: 'yyyy-MM-dd',
			max: '2099-09-09',
			value: currentDate
		});
	}

});